<?php


namespace App\Utils;


class ArrUtil {

    /**
     * ----树状结构
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public static function list2ree($list, $pk='id', $pid = 'pid', $child = 'children', $root = 0)
    {
        $tree = [];
        if(is_array($list)) {
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }


    public static function buildRouteNode($itemData)
    {
//        $itemData->alias = \str_replace('_', '', $itemData->path);
//        $itemData->alias = camelize($itemData->alias, '/');
//        $path            = '/' . lcfirst($itemData->alias);

        $vueRouteItem = [
            'id' => $itemData->id,
            'pid' => $itemData->pid,
            'name' => $itemData->name,
            'path' => '/'. $itemData->path,
            'component' => $itemData->path,
            'hidden' => $itemData->is_menu ? false : true,
            'meta' => [
                'title' => $itemData->display_name,
                'icon' => $itemData->icon,
                'noKeepAlive' => false,
            ],

        ];

        return $vueRouteItem;
    }

    public static function buildRouteTree($routeList, $root = 0)
    {
        $tree = [];

        if (is_array($routeList)) {
            // 创建基于主键的数组引用
            $refer = [];
            foreach ($routeList as $key => $data) {
                $refer[$data['id']] =& $routeList[$key];
            }
            foreach ($routeList as $key => $data) {
                // 判断是否存在parent
                $parentId = $data['pid'];
                if ($root == $parentId) {
                    $tree[] =& $routeList[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent                        =& $refer[$parentId];
                        $parent['children'][]          =& $routeList[$key];
                    }
                }
                if ($parentId == 0){
                    $routeList[$key]['component'] = 'Layout';
                }
            }
        }
        return $tree;
    }

}
